package com.yulang.controller;

import com.yulang.entity.SysPermission;
import com.yulang.security.result.Result;
import com.yulang.service.SysPermissionService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/permission")
public class SystemPermissionController {


    public final static String HTML_PREFIX = "system/permission";

    @Autowired
    private SysPermissionService service;

    @PreAuthorize("hasAnyAuthority('sys:permission')")
    @GetMapping(value = {"/",""})
    public String user() {

        return HTML_PREFIX+"/permission-list";
    }

    @PreAuthorize("hasAnyAuthority('sys:permission:edit','sys:permission:add')")
    @GetMapping(value = {"/form/{id}","/form"})
    public String formEdit(@PathVariable(required = false) String id, Model model) {
        if(StringUtils.isNotEmpty(id)) {
            SysPermission permission = service.getById(id);
            model.addAttribute("permission",permission);
        }else{
            model.addAttribute("permission",new SysPermission());
        }
        return HTML_PREFIX + "/permission-form";
    }


    @ResponseBody
    @PreAuthorize("hasAnyAuthority('sys:permission:list')")
    @PostMapping({"/list","/form/permission/list","/permission/list"})
    public Result list() {
        List<SysPermission> list = service.list();
        return Result.ok(list);
    }



    @PreAuthorize("hasAnyAuthority('sys:permission:edit','sys:permission:add')")
    @PostMapping
    public String add(SysPermission permission) {
        service.saveOrUpdate(permission);
        return HTML_PREFIX+"/permission-list";
    }

    @ResponseBody
    @PostMapping("/{id}")
    public Result delete(@PathVariable String id) {
        service.deleteById(id);
        return Result.ok();
    }



}
